package cn.liuweiwei.controller;

import cn.liuweiwei.domain.ImgFile;
import cn.liuweiwei.service.FileService;
import cn.liuweiwei.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("files")
@CrossOrigin
public class FileController {

    @Value("${fileLocation}")
    private String fileLocation;
    @Value("${fileDir}")
    private String fileDir;
    private static Date date = new Date();

    @Autowired
    private FileService fileService;

    /*
    文件上传
     */
    @PostMapping("upload")
    public Result upload(MultipartFile imgFile) {
        try {
            // 获得 classpath 的绝对路径
            String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
            File newFile = new File(realPath);
            // 如果文件夹不存在、则新建
            if (!newFile.exists()) newFile.mkdirs();
            // 上传
            String fileName = date.getTime() + "@" + imgFile.getOriginalFilename();
            imgFile.transferTo(new File(newFile, fileName));
            ImgFile file = new ImgFile().setFileName(fileName)
                    .setUrl(fileDir + "/" + fileName)
                    .setCreateTime(new Date());
            return Result.successWithObj(fileService.insertFileWithReturn(file));
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("上传失败");
        }
    }


    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
        // 获得文件输入流
        FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
        // 设置响应头、以附件形式打开文件
        response.setHeader("content-disposition", "attachment; fileName=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        inputStream.close();
    }

    /**
     * 分页查询文件
     *
     * @param page  当前页
     * @param limit 每页条数
     * @return
     */
    @GetMapping("/{page}/{limit}")
    public Result findFile(@PathVariable("page") String page,
                           @PathVariable("limit") String limit) {
        return Result.successWithObj(fileService.findFileByPage(page, limit));
    }

    /**
     * 通过文件名模糊查询文件数据
     *
     * @param name
     * @return
     */
    @GetMapping("{name}")
    public Result findFileByName(@PathVariable("name") String name) {
        return Result.successWithObj(fileService.findFilesByName(name));
    }

    @DeleteMapping("{id}")
    public Result deleteFile(@PathVariable("id") String id) {
        try {
            fileService.deleteFile(id);
            return Result.success("删除文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除文件失败");
        }
    }

}
